﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections;
using YK.Framework.Container;

namespace YK.Framework.Mvc
{
    public class ClassicControllerFactory : DefaultControllerFactory
    {       
        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            IController controller = ClassicContainer.GetObject(controllerName) as IController;

            if (controller == null)
            {
                controller = base.CreateController(requestContext, controllerName);
            }           

            AddActionInvokerTo(controller);

            return controller;
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            IController controller = null;

            if (controllerType != null)
            {
                var controllers = ClassicContainer.GetObjects(controllerType);

                if (controllers.Count > 0)
                {
                    controller = (IController)controllers.Cast<DictionaryEntry>().First().Value;
                }
            }
            else
            {               
                controller = base.GetControllerInstance(requestContext, controllerType);
            }

            AddActionInvokerTo(controller);

            return controller;
        }

        protected virtual void AddActionInvokerTo(IController controller)
        {
            if (controller == null)
                return;

            if (typeof(Controller).IsAssignableFrom(controller.GetType()))
            {
                ((Controller)controller).ActionInvoker = new ClassicActionInvoker();
            }
        }
    }
}